package com.lv.config;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

import static org.apache.shiro.web.filter.mgt.DefaultFilter.anon;

@Configuration
public class ShiroConfig {
    //创建ShiroFilterFactoryBean   配置过滤器工厂
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Autowired DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();

        //Shiro的过滤器里面,优先放过某些,然后我们才可以拦截所以等等,所以我们需要一个
        //怎么存进去的就怎么取出来的map   有序的map
        Map<String,String> map = new LinkedHashMap<>();
        //配置的过滤器,就是那些路径可以不用登录,那些路径必须登录,那些路径必须有权限等到
        //Key表示路径 , value 叫:过滤器,表示我们当前路径如何过滤,放过还是啥的
        //   anon  :  表示不需要登录直接访问
        //   authc :  表示必须登录才可以访问
        //   perms[] : []里面写权限字符串
        //   logout :  退出登录的过滤器
        map.put("/seller/login","anon");
        map.put("/seller/register","anon");
        map.put("/css/**","anon");
        map.put("/img/**","anon");
        map.put("/plugins/**","anon");
        map.put("/**","authc");//一定是放在左后
        factoryBean.setFilterChainDefinitionMap(map);
        //跳转登录页面
        factoryBean.setLoginUrl("/login");
        //需要将安全管理器放入过滤器工厂类中
        factoryBean.setSecurityManager(defaultWebSecurityManager);

        return factoryBean;
    }

    //创建DefaultWebSecurityManager  安全管理器
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(@Autowired LoginRealm loginRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联Realm
        securityManager.setRealm(loginRealm);
        return securityManager;
    }

    //实例化LoginRealm
    @Bean
    public LoginRealm loginRealm(@Autowired HashedCredentialsMatcher hashedCredentialsMatcher) {
        LoginRealm realm = new LoginRealm();
        realm.setCredentialsMatcher(hashedCredentialsMatcher);
        return realm;
    }

    //配置加密类
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        //配置加密算法 MD5
        matcher.setHashAlgorithmName("MD5");
        //迭代次数
        matcher.setHashIterations(3);
        //设置加密编码
        matcher.setStoredCredentialsHexEncoded(true);
        return matcher;
    }

    /*
    *   配置ShiroDialect  用与thymeleaf和shiro便签使用    禁用按钮
    * */
//    @Bean
//    public ShiroDialect getShiroDialect(){
//        return new ShiroDialect();
//    }
}
